

from fuzzy.utils import belongs_to

class MembershipFunctionMixin:
    def degreeOf(self,aCrisp):
        """the degree of a crisp number"""
        raise NotImplementedError("degreeOf() neeeds to be overwritten in subclasses")
    
    def __call__(self,aCrisp):
        return self.degreeOf(aCrisp)



class TriFuzzyMember(object,MembershipFunctionMixin):
    
    def __init__(self,name,a1,a2,am):
        
        self.a1 = a1
        self.am = am
        self.a2 = a2
        
        self.name = name

    def degreeOf(self, aCrisp):
        if belongs_to(aCrisp, self.a1, self.am):
            return (aCrisp - self.a1) / float(self.am - self.a1)
        elif belongs_to(aCrisp, self.am, self.a2):
            return (aCrisp - self.a2) / float(self.am - self.a2)
        else:
            return 0.0
        
    def __str__(self):
        return """FuzzyMember: %s 
        shape = TRIANGULAR 
        values = %s """ % (self.name,[self.a1,self.am,self.a2])
        
    def __eq__(self,aFuzzy):
        if not issubclass(TriFuzzyMember,aFuzzy.__class__):
            return False
        
        ret = self.a1 == aFuzzy.a1
        ret = ret and self.a2 == aFuzzy.a2
        ret = ret and self.am == aFuzzy.am
        
        return ret
    
    def __add__(self,aFuzzy):
        return TriFuzzyMember(self.name,self.a1 + aFuzzy.a1, self.a2 + aFuzzy.a2, self.am + aFuzzy.am)
    
    
        
    
    
  
class TrapFuzzyMember(object,MembershipFunctionMixin):
    
    def __init__(self,name,a1,a2,b1,b2):
          self.name = name
          self.a1 = a1
          self.b1 = b1
          self.b2 = b2
          self.a2 = a2

    def degreeOf(self, aCrisp):
        if aCrisp >= self.a1 and aCrisp <= self.b1:
            return (aCrisp - self.a1) / float(self.b1 - self.a1)
        elif aCrisp >= self.b1 and aCrisp <= self.b2:
            return 1.0
        elif aCrisp >= self.b2 and aCrisp <= self.a2:
            return (aCrisp - self.a2) / float(self.b2 - self.a2)
        else:
            return 0.0

    def __str__(self):
        return """FuzzyMember: %s 
        shape = TRAPEZIOIDAL 
        values = %s """ % (self.name,[self.a1,self.b1,self.b2,self.a2])        
    
    def __eq__(self,aFuzzy):
        if not issubclass(TrapFuzzyMember,aFuzzy.__class__):
            return False
        
        ret = self.a1 == aFuzzy.a1
        ret = ret and self.a2 == aFuzzy.a2
        ret = ret and self.b1 == aFuzzy.b1
        ret = ret and self.b2 == aFuzzy.b2
        return ret

a3 = TriFuzzyMember("test",1,2,3)
a2 = TriFuzzyMember("test",1,2,3)
a1 = TrapFuzzyMember("test1",1,2,3,4)

print a1== a2
print a1(2.5),a1(3),a1(4)
print (a2+a3)(3)

    